<template>
  <el-select class="margin10px" v-model="selectedExam" clearable placeholder="请选择考试" style="width: 220px" size="large"
    @change="handleSelectChange">
    <el-option v-for="item in examOptions" :key="item.value" :label="item.label" :value="item.value" />
  </el-select>
  <el-table :data="state.examRecords" border style="width: 100%;" header-background="#f2f3f4">
    <el-table-column property="examName" label="考试名称" />
    <el-table-column property="examTime" label="参考时间" />
    <el-table-column property="referee" label="参考人" />
    <el-table-column property="logicScore" label="逻辑题得分" />
    <el-table-column property="isReviewed" label="是否批阅" />
    <el-table-column property="totalScore" label="总分" />
    <el-table-column label="操作">
      <template v-slot="scope">
        <el-button v-if="scope.row.isReviewed === '未批阅'" type="primary"
          @click="gotoMarkExam(scope.row.recordId)"><el-icon>
            <View />
          </el-icon>&nbsp;去批阅</el-button>
        <el-button v-else type="warning" disabled><el-icon>
            <Hide />
          </el-icon>&nbsp;已批阅</el-button>
      </template>
    </el-table-column>
  </el-table>
  <br />
  <div class="demo-pagination-block">
    <div class="demonstration"></div>
    <el-pagination v-model:current-page="state.pageNum" v-model:page-size="state.pageSize" :page-sizes="[5, 10, 15, 20]"
      :page-size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
      :total="state.total" @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, inject } from 'vue';
import { useRouter } from 'vue-router';
const router = useRouter()
// 下拉列表选择的考试
const selectedExam = ref('');
// 所有考试名
const examOptions = ref([]);
import {
  getAllExamInfo,
  getUserById,
  getExamRecord,
} from '@/api/examControl/MarkManage'
// 定义组件状态
const state = reactive({
  examRecords: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const size = ref('default');
const background = ref(false);
const disabled = ref(false);

// 处理分页大小改变
const handleSizeChange = (val: number) => {
  state.pageSize = val;
  fetchExamRecords();
};

// 处理当前页改变
const handleCurrentChange = (val: number) => {
  state.pageNum = val;
  fetchExamRecords();
};

// 处理下拉列表选择改变
const handleSelectChange = (val: string) => {
  fetchExamRecords();
};

// 获取考试选项
async function fetchExamOptions() {
  try {
    const  {data} = await getAllExamInfo();
    examOptions.value = data.data.map((exam: any) => ({
      value: exam.examId,
      label: exam.examName,
    }));
  } catch (error) {
    console.error('获取考试选项时出错:', error);
  }
};

// 根据 userId 获取用户名
async function fetchUserName(userId: number) {
  try {
    const {data} = await getUserById(userId);
    return data.data.username || '未知';
  } catch (error) {
    console.error(`获取用户 ${userId} 时出错:`, error);
    return '未知';
  }
}

// 获取考试记录并根据 userId 获取用户名
async function fetchExamRecords() {
  try {
    const params: any = {
      pageNo: state.pageNum,
      pageSize: state.pageSize,
    };
    // 如果选择了下拉列表中的考试，附加 examId 参数
    if (selectedExam.value) {
      params.examId = selectedExam.value;
    }
    const {data} = await getExamRecord(params);

    const examRecords = [];
    for (const record of data.data.examRecords) {
      const username = await fetchUserName(record.userId);
      examRecords.push({
        // 剩余参数
        ...record,
        // 在examOptions.value数组中找到一个对象，该对象的value属性与record对象的examId属性相等。find函数返回找到的第一个匹配项，如果没有找到匹配项，则返回undefined。
        examName: examOptions.value.find((exam) => exam.value === record.examId)?.label || '',
        isReviewed: record.totalScore !== null ? '已批阅' : '未批阅',
        totalScore: record.totalScore !== null ? record.totalScore : 0,
        referee: username,
      });
    }

    state.examRecords = examRecords;
    state.total = data.data.total;
  } catch (error) {
    console.error('获取考试记录时出错:', error);
  }
}

// 切换到阅卷组件
function gotoMarkExam(recordId: number) {
  router.push({ path: `/home/markExam/${recordId}`});
}

// 组件挂载时调用
onMounted(() => {
  fetchExamOptions();
  fetchExamRecords();
});
</script>

<style scoped>
.margin10px
{
  margin-bottom: 10px;
}
</style>
